package com.sumer.proxy.jdk.proxy.cglib.proxy;

import com.sumer.proxy.jdk.proxy.Transaction;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    private final Transaction transaction;

    public CglibProxy(Transaction transaction) {
        this.transaction = transaction;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        Object object = null;
        if ("add".equals(method.getName())){
            transaction.begin();
            object = methodProxy.invokeSuper(o, objects);
            transaction.commit();
        }else {
            object = methodProxy.invokeSuper(o, objects);
        }
        return object;
    }
}
